{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bf3efdca-9206-4bde-a5f0-95d20efac12e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "迭代 1 次收敛\n",
      "方程组的解为： [0 0 0 0]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "def gauss_seidel(A, b, x0, tol=1e-6, max_iter=1000):\n",
    "    n = len(b)\n",
    "    x = x0.copy()\n",
    "    for k in range(max_iter):\n",
    "        x_new = x.copy()\n",
    "        for i in range(n):\n",
    "            # 计算当前行的和\n",
    "            s = np.dot(A[i, :i], x_new[:i]) + np.dot(A[i, i+1:], x[i+1:])\n",
    "            x_new[i] = (b[i] - s) / A[i, i]\n",
    "        # 判断收敛\n",
    "        if np.linalg.norm(x_new - x) < tol:\n",
    "            print(f\"迭代 {k+1} 次收敛\")\n",
    "            return x_new\n",
    "        x = x_new\n",
    "    raise ValueError(\"迭代未收敛\")\n",
    "\n",
    "# 输入数据\n",
    "A = np.array([\n",
    "    [2, 2, 3, 1],\n",
    "    [4, 7, 2, 5],\n",
    "    [2, 4, 5, 2],\n",
    "    [4, 6, 1, 4]\n",
    "])\n",
    "b = np.array([1, 4, 3, 1])\n",
    "x0 = np.array([0, 0, 0, 0])\n",
    "\n",
    "# 求解\n",
    "x = gauss_seidel(A, b, x0)\n",
    "print(\"方程组的解为：\", x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d28a7d11-11db-459f-adc1-ee069d4cdffa",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "fac99a8f-524f-4ef3-813e-657c2e293e3b",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "Gauss-Seidel 迭代未收敛",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[9], line 25\u001b[0m\n\u001b[0;32m     22\u001b[0m j \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray([\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m])\n\u001b[0;32m     24\u001b[0m \u001b[38;5;66;03m# 求解\u001b[39;00m\n\u001b[1;32m---> 25\u001b[0m x \u001b[38;5;241m=\u001b[39m gauss_seidel(G, L, j)\n\u001b[0;32m     26\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m方程组的解为：\u001b[39m\u001b[38;5;124m\"\u001b[39m, x)\n",
      "Cell \u001b[1;32mIn[9], line 13\u001b[0m, in \u001b[0;36mgauss_seidel\u001b[1;34m(A, b, x0, tol, max_iter)\u001b[0m\n\u001b[0;32m     11\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m x_new\n\u001b[0;32m     12\u001b[0m     x \u001b[38;5;241m=\u001b[39m x_new\n\u001b[1;32m---> 13\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mGauss-Seidel 迭代未收敛\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "\u001b[1;31mValueError\u001b[0m: Gauss-Seidel 迭代未收敛"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "def gauss_seidel(A, b, x0, tol=1e-6, max_iter=1000):\n",
    "    n = len(A)\n",
    "    x = x0.copy()\n",
    "    for _ in range(max_iter):\n",
    "        x_new = np.zeros(n)\n",
    "        for i in range(n):\n",
    "            s = np.dot(A[i, :i], x_new[:i]) + np.dot(A[i, i+1:], x[i+1:])\n",
    "            x_new[i] = (b[i] - s) / A[i, i]\n",
    "        if np.linalg.norm(x_new - x) < tol:\n",
    "            return x_new\n",
    "        x = x_new\n",
    "    raise ValueError(\"Gauss-Seidel 迭代未收敛\")\n",
    "\n",
    "G = np.array([\n",
    "    [2, 2, 3, 1],\n",
    "    [4, 7, 2, 5],\n",
    "    [2, 4, 5, 2],\n",
    "    [4, 6, 1, 4]\n",
    "])\n",
    "L = np.array([1, 4, 3, 1])\n",
    "j = np.array([0, 0, 0, 0])\n",
    "\n",
    "# 求解\n",
    "x = gauss_seidel(G, L, j)\n",
    "print(\"方程组的解为：\", x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0f9122b7-8409-49cd-910c-bac78c1c82f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "方程组的解为： (array([ 3.32905843e+202,  1.22381174e+203, -3.73530505e+202,\n",
      "       -2.07524083e+203]), 4000, False)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "def gauss_seidel(A, b, x0=None, max_iter=4000, tol=1e-6):\n",
    "    n = len(b) \n",
    "    if A.shape != (n, n):\n",
    "        raise ValueError(\"系数矩阵A的维度必须为n×n\")\n",
    "    if any(np.diag(A) == 0):\n",
    "        raise ValueError(\"系数矩阵A的对角元素不能为零\")\n",
    "    if x0 is None:\n",
    "        x = np.zeros_like(b, dtype=np.float64)\n",
    "    else:\n",
    "        x = np.array(x0, dtype=np.float64)\n",
    "    converged = False\n",
    "    \n",
    "    for k in range(max_iter):\n",
    "        x_old = x.copy()  \n",
    "        for i in range(n):\n",
    "            sum_val = b[i]\n",
    "            for j in range(n):\n",
    "                if j != i:\n",
    "                    sum_val -= A[i, j] * x[j]\n",
    "            x[i] = sum_val / A[i, i]\n",
    "        error = np.linalg.norm(x - x_old, ord=np.inf)\n",
    "        if error < tol:\n",
    "            converged = True\n",
    "            return x, k + 1, converged\n",
    "    \n",
    "    return x, max_iter, converged\n",
    "\n",
    "A= np.array([\n",
    "    [2, 2, 3, 1],\n",
    "    [4, 7, 2, 5],\n",
    "    [2, 4, 5, 2],\n",
    "    [4, 6, 1, 4]\n",
    "])\n",
    "b = np.array([1, 4, 3, 1])\n",
    "x0 = np.array([0, 0, 0, 0])\n",
    "\n",
    "\n",
    "x = gauss_seidel(A, b, x0)\n",
    "print(\"方程组的解为：\", x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "73c362f2-8009-4195-a9e5-ed5200a8840c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "迭代 16 次收敛\n",
      "方程在 x0=1.5 附近的实根为： 1.0000009743812768\n"
     ]
    }
   ],
   "source": [
    "def simplified_newton(f, df, x0, tol=1e-6, max_iter=1000):\n",
    "    df_x0 = df(x0)\n",
    "    x = x0\n",
    "    for k in range(max_iter):\n",
    "        fx = f(x)\n",
    "        if abs(fx) < tol:\n",
    "            print(f\"迭代 {k+1} 次收敛\")\n",
    "            return x\n",
    "        x = x - fx / df_x0\n",
    "    raise ValueError(\"迭代未收敛\")\n",
    "\n",
    "\n",
    "def f(x):\n",
    "    return x**3 - 3*x**2 + 4*x - 2\n",
    "\n",
    "def df(x):\n",
    "    return 3*x**2 - 6*x + 4\n",
    "\n",
    "x0 = 1.5\n",
    "root = simplified_newton(f, df, x0)\n",
    "print(f\"方程在 x0={x0} 附近的实根为：\", root)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2201e634-d60c-4dd6-be0a-28444586c440",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:base] *",
   "language": "python",
   "name": "conda-base-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
